/*
 * @Description: 
 * @version: 
 * @Author: zyc
 * @Date: 2022-09-13 10:49:48
 * @LastEditors: ywl
 * @LastEditTime: 2023-05-16 11:54:21
 */

import { baseUrlHttp } from '@/env/env.config'
import { useSysStore } from '@/stores/sys'
import pinia from '@/_pinia'
import { showToast } from '@/utils/tip'

const sys = useSysStore(pinia)
let repeatLoginNum = 0
/**请求接口
 * @method http
 * @param {String} url 接口地址
 * @param {Object} data 接口参数
 * @param {Object} option 接口配置信息，可选
 * @return {Object} Promise
 */
const api = (url: any, data: any = {}, option: any = { autoRedirect: true }): Promise<any> => {

	const header = {
		'X-Access-Token': sys.getToken
	}

	return new Promise((resolve, reject) => {
		
		const apiUrl = baseUrlHttp + '/ihomesaas/client' + url
		console.log(apiUrl, 'api接口.....');
		console.log(data, 'api参数....')
		
		uni.request({
			url: apiUrl,
			method: option.method || 'post', // 默认 post 请求
			header,
			data: data,
			success: res => { // 服务器成功返回的回调函数
				if (res.statusCode === 200) {
					const result: any = res.data;
					if (result.code === 200) {
						resolve(result.result)
						return;
					} else {
						setTimeout(() => {
							showToast(result.message || `系统错误，状态码：${result.code}`);
						}, 200);
						reject(result);
						return;
					}
				} else { // 返回值非 200，强制显示提示信息
					if (res.statusCode === 401) {
						if (option.autoRedirect) {
							repeatLoginNum++;
							if (repeatLoginNum > 3) return
							uni.reLaunch({
								url: "/pages/start"
							})
							showToast('[' + res.statusCode + '] 登陆失效');
						}
						reject(res);
						return;
					}
				}
			},
			fail: (err) => { // 接口调用失败的回调函数
				console.error(err.errMsg);
				if (err.errMsg == 'request:fail url not in domain list') {
					showToast('服务器域名未配置');
				} else if (err.errMsg.includes('CONNECTION_TIMED_OUT')) {
					showToast('网络连接超时');
				} else if (err.errMsg.includes('ERR_NAME_NOT_RESOLVED')) {
					showToast('域名未解析');
				} else {
					showToast("网络异常：" + err.errMsg);
				}
				reject(err.errMsg);
			}
		})
	})
}
/**get请求
 * @param {*} url
 * @param {*} data
 * @param {*} option
 * @return {*}
 */
const getApi = async (url: any, data: any = {}, option: any = {}): Promise<any> => {
	option.method = 'get'
	return await api(url, data, option)
}
/**post请求
 * @param {*} url
 * @param {*} data
 * @param {*} option
 * @return {*}
 */
const postApi = async (url: any, data: any = {}, option: any = {}): Promise<any> => {
	option.method = 'post'
	return await api(url, data, option)
}
/**put请求
 * @param {*} url
 * @param {*} data
 * @param {*} option
 * @return {*}
 */
const putApi = async (url: any, data: any = {}, option: any = {}): Promise<any> => {
	option.method = 'put'
	return await api(url, data, option)
}
/**delete请求
 * @param {*} url
 * @param {*} data
 * @param {*} option
 * @return {*}
 */
const deleteApi = async (url: any, data: any = {}, option: any = {}): Promise<any> => {
	const params = Object.keys(data).map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key])).join("&")
	url = `${url}?${params}`
	option.method = 'delete'
	return await api(url, undefined, option)
}

export { getApi, postApi, putApi, deleteApi }
